package com.sky.web.example.controller.test;

import com.sky.common.annotation.Anonymous;
import com.sky.common.core.domain.AjaxResult;
import com.sky.web.example.bean.User;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Anonymous
@RestController
@RequestMapping("/user/rest")
public class UserRestController {

    // 使用静态Map模拟用户数据存储
    private static Map<Integer, User> userMap = new HashMap<>();

    // 静态初始化块，填充模拟数据
    static {
        userMap.put(1, new User("Alice", 18));
        userMap.put(2, new User("Bob", 20));
    }

    // 处理GET请求，根据ID返回特定用户的详细信息
    @GetMapping("/{id}")
    public AjaxResult getUserById( @PathVariable int id) {
        User user = userMap.get(id);
        if (user != null) {
            return AjaxResult.success("find success!",user);
        } else {
            return AjaxResult.error("User not found");
        }
    }

    // 处理DELETE请求，根据ID删除用户
    @DeleteMapping("/{id}")
    public AjaxResult deleteUserById(@PathVariable int id) {
        User removedUser = userMap.remove(id);
        if (removedUser != null) {
            return AjaxResult.success("User deleted successfully");
        } else {
            return AjaxResult.error("User not found");
        }
    }

    // 处理PUT请求，根据ID更新用户信息
    @PutMapping("/{id}")
    public AjaxResult updateUser(@PathVariable int id, @RequestBody User updatedUser) {
        if (userMap.containsKey(id)) {
            userMap.put(id, updatedUser);
            return AjaxResult.success("User updated successfully");
        } else {
            return AjaxResult.error("User not found");
        }
    }

    // 处理POST请求，新增用户
    @PostMapping
    public AjaxResult addUser(@RequestBody User newUser) {
        int newUserId = userMap.size() + 1; // 简单生成唯一ID
        userMap.put(newUserId, newUser);
        return AjaxResult.success("User added successfully", newUser);
    }
}